package com.bfmet.crawler;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;

import com.bfmet.common.DAOService;
import com.bfmet.common.base.EntityBase;
import com.bfmet.common.base.UtilBase;

public abstract class Spider extends UtilBase implements Runnable {

	protected boolean exist(EntityBase entity) {
		EntityManager em = DAOService.getEM();
		try {
			Metamodel metamodel = em.getEntityManagerFactory().getMetamodel();
			EntityType<?> pClass = metamodel.entity(entity.getClass());

			Query query = em.createQuery("select n from " + pClass.getName()
					+ " n where n.name=:name");
			query.setParameter("name", entity.getName());
			return !query.getResultList().isEmpty();
		} finally {
			em.close();
		}
	}

	protected void save(EntityBase entity) {
		if (!this.exist(entity)) {
			if (entity.getCreateTime() == null) {
				entity.setCreateTime(new Date());
			}
			DAOService.persist(entity);
		} else {
			this.log(entity.getClass().getSimpleName() + "|" + entity.getName()
					+ " exists");
		}
	}
}
